/**
*  
* @Function 数据质量报告Controller
* @ProjectName credit-data-platform 
* @PackageName com.py.credit.controller    
* @FileName DataQualityController.java    
* @Date 2018年7月11日上午10:24:06
* @Author Min DongXv
* @Copyright (c) 2018, 金电联行 All Rights Reserved.   
*   
*/
package com.py.credit.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.DataQualityDetailEntity;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.FunctionReportFieldEnum;
import com.py.credit.service.FunctionReportService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.MapCache;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * 
 * @Function 数据质量报告Controller
 * @ClassName DataQualityController
 * @Date 2018年7月11日 上午10:24:06
 * @Author Min DongXv
 * 
 */
@RestController
@RequestMapping(value = "/functionReport")
public class FunctionReportController extends BaseController {

	private static final String DATA_QUALITY_ID = "functionReportId";

	@Value("${absolutepath}")
	private String absolutepath;

	@Value("${pdfPath}")
	private String pdfPath;

	@Value("${pdfJsPath}")
	private String pdfJsPath;

	@Value("${googlePath}")
	private String googlePath;
	 
	@Value("${pdfzlbg}")
	private String pdfzlbg;

	@Autowired
	private FunctionReportService functionReportService;

	@Autowired
	private RemoteBaseService remoteBaseService;

	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		return new RestServiceResult<List<OptionalColumn>>(FunctionReportFieldEnum.getOptionalColumns());

	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		return new RestServiceResult<List<OptionalColumn>>(FunctionReportFieldEnum.getAdvancedConditionColumns());
	}

	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("DataQualityController#addShowColunms", "未获取到当前用户信息！");
				return result;
			}
			MapCache.set(userInfo.getId() + "_" + DATA_QUALITY_ID, columns);
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return new RestServiceResult<String>();
	}

	/**
	 * 
	 * @api {get} /dataQuality/dataQualityList.json 数据质量报告列表
	 * @apiName dataQualityList
	 * @apiVersion 0.0.1
	 * @apiGroup 数据质量报告
	 * @apiParam {String} condition 高级查询条件
	 * @apiParam {Page} page 分页
	 * @apiParamExample {json} 请求参数示例 {"condition":""}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {List} data 结果集
	 * @apiSuccess {Integer} id 编号
	 * @apiSuccess {String} dateRange 期数
	 * @apiSuccess {int} deptNum 部门数
	 * @apiSuccess {int} dataNum 报送数据
	 * @apiSuccess {String} scount 成功入库数
	 * @apiSuccess {String} fcount 错误数据
	 * @apiSuccess {String} rrate 重复率
	 * @apiSuccess {String} wrate 待关联率
	 * @apiSuccess {String} srate 成功率
	 * @apiSuccess {String} fileName 文件名称
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@ResponseBody
	@RequestMapping("/functionReportList.json")
	public RestServiceResult<List<Map<String, Object>>> dataQualityList(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("DataQualityController#dataQualityList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + DATA_QUALITY_ID);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? FunctionReportFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		try {
			List<Map<String, Object>> data = functionReportService.functionReportListByConditionForPage(showColumns,
					new String[] { "id" }, page, condition);
			result.setCount(page.getTotalCount());
			result.setData(data);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("DataQualityController#dataQualityList", "获取数据质量报告列表异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("获取数据质量报告列表异常！");
			return result;
		}
	}


	/**
	 * 
	 * @api {get} /dataQuality/pdfDownload.json 数据质量报告下载
	 * @apiName pdfDownload
	 * @apiVersion 0.0.1
	 * @apiGroup 数据质量报告
	 * @apiParam {String} fileName 文件名
	 * @apiParam {String} dateRange 期数
	 * @apiParamExample {json} 请求参数示例 {"fileName":"pdf", "dateRange":"201807"}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 */
	@ResponseBody
	@RequestMapping(value = "/pdfDownload.json")
	@IgnoreAuthority
	public RestServiceResult<Object> pdfDownload(HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "", required = true) String id) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			functionReportService.pdfDownload(id, response);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("DataQualityController#pdfDownload", "数据质量报告下载异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("数据质量报告下载异常！");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /dataQuality/createDataQualityReport.json 手动生成数据质量报告
	 * @apiName createDataQualityReport
	 * @apiVersion 0.0.1
	 * @apiGroup 数据质量报告
	 * @apiParam {String} dateRange 期数
	 * @apiParamExample {json} 请求参数示例 {"dateRange":"201707"}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 */
	@ResponseBody
	@RequestMapping(value = "/createFunctionReport.json")
	@IgnoreAuthority
	public RestServiceResult<Object> createDataQualityReport(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "startTime", defaultValue = "", required = true) String startTime,
			@RequestParam(value = "endTime", defaultValue = "", required = true) String endTime) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
//			String data = functionReportService.functionReportReport(pdfJsPath, pdfPath,googlePath, startTime,endTime,"S", response, request);

			functionReportService.dataQualityReport(pdfzlbg, startTime,endTime, response, request,pdfJsPath,googlePath,absolutepath,"Z");
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("DataQualityController#createDataQualityReport",
					"手动生成数据质量报告异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("手动生成数据质量报告异常！ERROR：" + e.getMessage());
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /dataQuality/dataQualityReportTask.do 定时任务生成数据质量报告
	 * @apiName dataQualityReportTask
	 * @apiVersion 0.0.1
	 * @apiGroup 数据质量报告
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 */
	@ResponseBody
	@RequestMapping(value = "/functionReportTask.do")
	@IgnoreAuthority
	public RestServiceResult<Object> dataQualityReportTask(HttpServletRequest request, HttpServletResponse response) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		Calendar calendar = Calendar.getInstance();
		String dateRange = sdf.format(calendar.getTime());
		try {
//			functionReportService.functionReportReport(pdfJsPath, pdfPath,googlePath, dateRange,null,"Z", response, request);
			functionReportService.dataQualityReport(pdfzlbg, dateRange,null, response, request,pdfJsPath,googlePath,absolutepath,"Z");
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("DataQualityController#dataQualityReportTask",
					"定时任务生成数据质量报告异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("定时任务生成数据质量报告异常！ERROR：" + e.getMessage());
			return result;
		}
	}
	/**
	 * 
	 * @api {get} /dataQuality/dataQualityPdfReport.do pdf报告模板
	 * @apiName dataQualityPdfReport
	 * @apiVersion 0.0.1
	 * @apiGroup 数据质量报告
	 * @apiParam {String} dateRange 期数
	 * @apiParamExample {json} 请求参数示例 {"dateRange":"201807"}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 */
	@RequestMapping(value = "/dataQualityPdfReport.do")
	@IgnoreAuthority
	public void dataQualityPdfReport(HttpServletResponse response,
			@RequestParam(value = "startTime", defaultValue = "", required = true) String startTime,
			@RequestParam(value = "endTime", defaultValue = "", required = true) String endTime) {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out;
		try {
			String data;
			try {
				data = functionReportService.createPdfHtml(startTime,endTime);
				out = response.getWriter();
				out.println(data);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (IOException e) {
			ExceptionLogger.error("DataQualityController#dataQualityPdfReport", "页面pdf报告！ERROR：" + e.getMessage(), e);
		}
	}
	
	@ResponseBody
	@IgnoreAuthority
	@RequestMapping(value = "/dataQualityReport.json")
	public RestServiceResult<JSONObject> dataQualityReport(HttpServletRequest request,
			@RequestParam(value = "id", defaultValue = "", required = true) String id) {
		RestServiceResult<JSONObject> result = new RestServiceResult<JSONObject>();
		try {
			DataQualityDetailEntity data = functionReportService.dataQualityDetail(id);
			if (null != data && StringUtils.isNotBlank(data.getContent())) {
				result.setData(JSONObject.parseObject(data.getContent()));
			}
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("DataQualityController#dataQualityDetail", "获取数据质量报告异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("获取数据质量报告异常！");
			return result;
		}
	}
}
